package com.jxpanda.spring.module.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jxpanda.infrastructure.core.tollkit.json.JacksonBuilder;
import com.jxpanda.infrastructure.core.tollkit.json.LongToStringSerializer;
import com.jxpanda.infrastructure.core.tollkit.json.NullSafeSerializer;
import com.jxpanda.spring.module.common.config.properties.JacksonProperties;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;

@RequiredArgsConstructor
public class JacksonConfigure {

    @Bean
    @ConditionalOnProperty(prefix = "panda.spring.common.jackson", name = "enable", havingValue = "true", matchIfMissing = true)
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            builder.serializerByType(Long.class, new LongToStringSerializer());
            builder.modules(JacksonBuilder.javaTimeModule());
        };
    }


    @RequiredArgsConstructor
    @AutoConfigureAfter(JacksonConfigure.class)
    public static class ObjectMapperConfigure {

        private final JacksonProperties jacksonProperties;
        private final ObjectMapper objectMapper;

        @PostConstruct
        public void configure() {
            if (jacksonProperties.isEnable()) {
                if (jacksonProperties.isWriteNullToEmpty()) {
                    objectMapper.getSerializerProvider().setNullValueSerializer(new NullSafeSerializer());
                }
            }
        }

    }

}
